package com.zline.foodraise.http;

import android.content.Context;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.util.LUtil;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;

/**
 * Created by heshantao on 15/7/10.
 * http 请求工具类
 */
@EBean
public class HttpUtil {
    private static final String LOG_TAG=HttpUtil.class.getSimpleName();
    //private static final String baseurl ="http://cc.line0.com/ws";//线上
    private static final String baseurl="http://staging.cc.line0.com/ws";//测试环境
    //private static final String baseurl="http://192.168.199.109:8080/ws";//调试环境
    static AsyncHttpClient client;
    @RootContext
    Context cxt;

    public static synchronized AsyncHttpClient getInstance() {
        if (client == null) {
            client = new AsyncHttpClient();
        }
        return client;
    }


    //get 方式
    public  void get(String url,AsyncHttpResponseHandler handler){
        addHeader("user-agent","chrome" );
        addHeader(Constant.ACCESSTYPE,Constant.ACCESSTYPE_ANDROID+"");
        client.get(cxt, url, handler);
    }

    public  void get(String url,RequestParams params,AsyncHttpResponseHandler handler){
        addHeader("user-agent","chrome" );
        addHeader(Constant.ACCESSTYPE,Constant.ACCESSTYPE_ANDROID+"");
        client.get(cxt, baseurl + url, params, handler);
    }
    //post 请求
    public  void post(String url,RequestParams params,AsyncHttpResponseHandler handler){
        LUtil.i(LOG_TAG, baseurl + url);
        addHeader("user-agent", "chrome");//需要加一个头设置否则会禁止访问
        addHeader(Constant.ACCESSTYPE,Constant.ACCESSTYPE_ANDROID+"");
        client.post(cxt, baseurl + url, params, handler);
    }

    //post 请求用于请求jsonObject 对象
    public  void post(String url,ByteArrayEntity entity,AsyncHttpResponseHandler handler){
        LUtil.i(LOG_TAG, baseurl + url);
        addHeader("user-agent", "chrome");//需要加一个头设置否则会禁止访问
        addHeader(Constant.ACCESSTYPE, Constant.ACCESSTYPE_ANDROID + "");
        client.post(cxt, baseurl + url, entity, "application/json", handler);
    }

    //添加请求头
    public  void addHeader(String header, String value) {
        getInstance();
        client.addHeader(header, value);
    }

    //用于设置响应的时间,主要用于多张图片上传
    public void setResponseTimeOut(int time){
        getInstance();
        client.setResponseTimeout(time);
    }


}
